import { agentConfig } from '$domain/model/agent/config';
import { StoragePath } from './simulationStoragePath';
import { StateMachine } from '$domain/service/stateMachine';
import { SimulationJob } from './simulationJob';
import { SimulationPath } from './simulationPath';
import { PreparingState } from './state/preparingState';
import { SimulationLogger } from './simulationLogger';
import { BaseSimulationJobState } from './state/baseJobState';
import { SimulationParameterService } from './service/parameterService';
export class SimulationJobRunner extends StateMachine<BaseSimulationJobState> {
  
  public jobId: string;
  public product: string;
  public logger: SimulationLogger;
  public storagePath: StoragePath;
  public simulationPath: SimulationPath;
  public simulationParameterService: SimulationParameterService;

  constructor(
    jobId: string,
    product: string,
    logger: SimulationLogger,
    simulationPath: SimulationPath,
    storagePath: StoragePath,
    simulationParameterService: SimulationParameterService)
  {
    super();
    this.jobId = jobId;
    this.product = product;
    this.logger = logger;
    this.storagePath = storagePath;
    this.simulationPath = simulationPath;
    this.simulationParameterService = simulationParameterService;
    this.transitionTo(new PreparingState());
  }

  getCurrentStateName() {
    return this.state.getStateName();
  }

  execute = async () => {
    await this.state.execute();
  }

  interrupt = async () => {
    await this.state.cancel();
  }
}

export function buildJobRunner(job: SimulationJob) {
  const storagePath = StoragePath.of(job.extra);
  const simulationPath = SimulationPath.of(job.product, job.id);
  const simulationLogger = new SimulationLogger(job.extra);

  if (agentConfig.ossPolicy === 'driver-run-only') {
    simulationLogger.disableOSS();
  }

  const simParameterService = new SimulationParameterService(simulationLogger, storagePath, simulationPath);
  return new SimulationJobRunner(job.id, job.product, simulationLogger, simulationPath, storagePath, simParameterService);
}

export const jobRunnerCache: {[jobId: string]: SimulationJobRunner } = {};